const { config } = require('../config');
const { logger } = require('../utils/logger');

function apiKeyMiddleware() {
  return (req, res, next) => {
    if (!config.requireApiKey) {
      return next();
    }

    const incomingKey = (req.headers['x-api-key'] || req.query.apiKey || '').toString();

    if (incomingKey === config.apiKey) {
      return next();
    }

    logger.warn({ path: req.path }, 'Request rejected due to invalid API key');
    res.status(401).json({ error: 'unauthorized', message: 'Invalid or missing API key' });
  };
}

module.exports = { apiKeyMiddleware };
